package ps.client.plugin.eq2.gui.dialog.curses.timer;

import java.util.Vector;


public class Timer implements Runnable {
	
	long startMillis;
    long lastMillis;
	
    boolean started = false;
	boolean running = true;
	boolean stop = false;
	
	Vector<TimerListener> listenerList = new Vector<TimerListener>();
	
	public void run() {
        try {
        	while (!started) {
        		Thread.sleep(100);
        	}
            while (running) {
                lastMillis = System.currentTimeMillis();
                long currentMillis = lastMillis - startMillis;
                if (!stop) {
                	fireTimerEvent((int)(currentMillis / 1000));
                }
                Thread.sleep(1000 - ((currentMillis) % 1000));
            }
        } catch (Exception ex) {
        }
    }
	
	public void start() {
		startMillis = System.currentTimeMillis();
        lastMillis = startMillis;
		started = true;
	}
		
	public void stop() {
		stop = true;
	}
	
	public void resume() {
		stop = false;
	}
	
	public void restart() {
		start();
		resume();
	}
	
	public void dispose() {
		started = true;
		running = false;
	}
	
	public void addTimerListener(TimerListener listener) {
		if (!listenerList.contains(listener)) {
			listenerList.add(listener);
		}
	}
	
	public void removeTimerListener(TimerListener listener) {
		listenerList.remove(listener);
	}
	
	public void removeAllTimerListener() {
		listenerList.clear();
	}
	
	protected void fireTimerEvent(int secs) {
		TimerEvent event = new TimerEvent(this, secs);
		for (int i = 0; i < listenerList.size(); i++) {
			listenerList.get(i).timerEvent(event);
		}
	}

}
